<?php

namespace IDock\Insurance\QHIC\Request;

use IDock\Http\Request;
use IDock\Http\RequestFormat;
use IDock\Http\RequestMethod;

class AllQHICRequest extends Request
{

    protected $method = RequestMethod::POST;

    protected $format = RequestFormat::RAW;

    protected $tradeNo = '';

    public $route = '';

    public $flowId = '';

    public function loadConfig(array $config): Request
    {
        $this->gateway = $config['gateway'] ?? '';

        $this->logsDir = $config['logsDir'] ?? '';

        $this->timeout = $config['timeout'] ?? '';

        $this->proxy = $config['proxy'] ?? '';

        $this->proxyPW = $config['proxyPW'] ?? '';

        $this->proxyAccount = $config['proxyAccount'] ?? '';

        return $this;
    }

    public function getTradeNo()
    {
        return $this->tradeNo;
    }

    public function setTradeNo()
    {
        $this->tradeNo = date('YmdHis') . rand(10000, 99999);
    }

    public function requestLogs($uuid, $inLog = true)
    {
        if (!$this->logsFile) {
            return;
        }

        if ($this->urlTip) {
            $url = $this->gateway;
            $urlLogs = date('Y-m-d H:i:s') . " FUN_TIPS " . $uuid . " " . $this->urlTip . ' ' . $url;
        } else {
            $urlLogs = date('Y-m-d H:i:s') . " URL      " . $uuid . " " . $this->gateway;
        }

        if (!$inLog) {
            return;
        }
        file_put_contents($this->logsFile, $urlLogs . "\r\n", FILE_APPEND);
        //header 日记
        if ($this->headers) {
            $encLogs = date('Y-m-d H:i:s') . " HEADER   " . $uuid . " " . json_encode($this->getHeaders(), JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE);
            file_put_contents($this->logsFile, $encLogs . "\r\n", FILE_APPEND);
        }
        if ($this->preParameter != $this->bizParam) {
            $encLogs = date('Y-m-d H:i:s') . " ENCRYPT  " . $uuid . " " . json_encode($this->preParameter, JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE);
            file_put_contents($this->logsFile, $encLogs . "\r\n", FILE_APPEND);
        }
        $reqLogs = date('Y-m-d H:i:s') . " REQUEST  " . $uuid . " " . $this->bizParam;
        file_put_contents($this->logsFile, $reqLogs . "\r\n", FILE_APPEND);
    }

    public function responseLogs($uuid, $data)
    {
        if (!$this->logsFile) {
            return;
        }
        $data = str_replace(["\r\n","\r","\n"],['','',''],$data);
        if(!empty($data)){
            $res = json_decode($data,true);
            if(isset($res['pdfFileByte'])){
                $res['pdfFileByte'] = '...';
                $data = json_encode($res);
            }
        }

        $repLogs = date('Y-m-d H:i:s') . " RESPONSE " . $uuid . " " . $data;

        file_put_contents($this->logsFile, $repLogs . "\r\n", FILE_APPEND);
    }

}
